<?php

namespace App\Api\Controllers;

use App\Models\BalanceRecord;
use App\Models\DealRecord;
use App\Models\Depot;
use App\Models\PlatformIncome;
use App\Models\User;
use Dingo\Api\Routing\Helpers;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use EasyWeChat\Payment\Order as PayOrder;


/**
 * Class SpreadController
 * @package App\Api\Controllers
 * 推广大使
 */
class SpreadController extends Controller
{
    use Helpers;

    /**
     * 名称：校园推广大使首页数据
     */
    public function index(){
        $user=$this->auth->user();
        return $this->response->array([
            'status_code'=>200,
            'message'=>'获取数据成功',
            'result'=>[
                'nickname'=>deal_emoji($user->nickname),
                'head_img'=>$user->head_img,
                'id'=>$user->id,
                'spread_status'=>$user->spread_status,
                'goods_total'=>Depot::where('user_id',$user->id)->count(),
                'spread_qrcode'=>$user->spread_qrcode
            ]
        ]);
    }

    /**
     * 名称：我推广的校友
     */
    public function spreadList(){
        $user=$this->auth->user();
        $spreadList=DB::table('users as u')
            ->leftjoin('balance_record as br','br.bespread_uid','=','u.id')
            ->where('u.spread_uid',$user->id)
            ->select('u.head_img','u.nickname','u.spread_status',DB::raw("sum(br.amount) as amount"),'u.id')
            ->groupBy('u.id')
            ->orderBy('u.id','desc')
            ->get();
        $totalMoney=0;
        $spreadNum=0;
        foreach ($spreadList as $v){
            $totalMoney+=$v->amount;
            $v->nickname=deal_emoji($v->nickname);
            $spreadNum++;
        }
        return $this->response->array([
            'status_code'=>200,
            'message'=>'获取数据成功',
            'result'=>[
                'spreadNum'=>$spreadNum,
                'spreadList'=>$spreadList,
                'totalMoney'=>$totalMoney
            ]
        ]);

    }



    /**
     * 获取支付需要签名数据
     */
    public function spreadSign()
    {
        $user=$this->auth->user();
        //检查是否有未支付的数据
        $dealRecord = DealRecord::where([['user_id',$user->id],['status',0],['type',1]])->first();
        if (!$dealRecord) {
            $dealRecordIn = [
                'user_id' => $user->id,
                'amount' => 19.9,
                'status' => 0,//未支付
                'description' => '推广助力金',
                'in_order_num' => order_sn(),
                'out_order_num' => '',
                'pay_type' => 0,//微信支付
                'type'=>1,//业务类型，推广助力金
            ];
            $dealRecord = DealRecord::create($dealRecordIn);
        }

        if (!$dealRecord) {
            return ['result' => 0, 'message' => '1.支付失败'];
        }

        //开始生成微信支付参数
        $attributes = [
            'trade_type' => 'JSAPI', // JSAPI，NATIVE，APP...
            'body' => '校园推广大使',
            'detail' =>'缴纳推广助力金',
            'out_trade_no' => $dealRecord->in_order_num,
            //'total_fee' => 1, // 单位：分
            'total_fee' => $dealRecord->amount * 100, // 单位：分
            'notify_url' => env('APP_API').'/spreadWechatPayBack', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'openid'=>User::find($dealRecord->user_id)->openid,
        ];

        $order = new PayOrder($attributes);
        $payment = app('wechat')->payment;
        $result = $payment->prepare($order);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
            $json = $payment->configForPayment($result->prepay_id,false);

            return $this->response->array([
                'status_code'=>200,
                'message'=>'准备支付',
                'result'=>$json
            ]);
        } else {
            return ['result' => 201, 'message' => '支付失败'];
        }

    }

    /**
     * 名称：推广助力金微信支付成功回调
     */
    public function spreadWechatPayBack()
    {
        $wechat=app('wechat');
        $response = $wechat->payment->handleNotify(function($notify, $successful){
            log_arr($notify);
            if($successful && $this->payCallBack($notify->out_trade_no,$notify->transaction_id)){
                return true;
            }
            return false; // 或者错误消息
        });

        return $response; // Laravel 里请使用：return $response;
    }

    /**
     * 名称：推广助力金回调处理逻辑
     */
    private function payCallBack($out_trade_no,$transaction_id)
    {


        if(!$out_trade_no || !$transaction_id){
            return false;
        }

        $dealRecord=DealRecord::where('in_order_num',$out_trade_no)->first();

        if(!$dealRecord){
            return false;
        }

        if($dealRecord->status==1){
            return true;//处理过了
        }

        $user=User::find($dealRecord->user_id);
        if(!$user){
            return false;
        }

        //需要生成推广二维码
        $qrcode=app('wechat')->qrcode;
        $result = $qrcode->forever($user->id);
        $ticket = $result->ticket;
        $spread_qrcode = $qrcode->url($ticket);
        if(!$spread_qrcode){
            return false;
        }

        $rollback = false;//回滚标志
        DB::beginTransaction();//开启事物
        //user表
        $user->spread_status=1;
        $user->spread_qrcode=$spread_qrcode;//二维码地址
        if(!$user->save()){
            $rollback=true;
            goto down;
        }

        //deal_record表
        $dealRecord->status=1;
        $dealRecord->out_order_num=$transaction_id;
        if(!$dealRecord->save()){
            $rollback=true;
            goto down;
        }
        $income=$dealRecord->amount;
        $spreader=User::find($user->spread_uid);
        if($spreader){
            //该用户存在推广大使
            $spreader->balance+=15;//增加推广大使余额
            $income-=15;//平台收益减少
            //记录日志
            if (!BalanceRecord::create([
                'user_id' => $spreader->id,
                'amount' => 15,
                'description' => "作为推广大使，您推广的某个用户也成为了推广大使，恭喜您获得了返利。",
                'type' => 3,
                'bespread_uid'=>$user->id,
                'action' => '+'])
            ) {
                $rollback = '日志';
                goto down;
            }
        }
        //平台收益
        if(!PlatformIncome::create([
            'in_order_num'=>$dealRecord->in_order_num,
            'amount'=>$income,
            'description'=>'推广助力金',
            'type'=>1
        ])){
            $rollback = true;
            goto down;
        }

        down:
        if ($rollback) {
            DB::rollback();
            return false;
        } else {
            DB::commit();
            return true;
        }

    }

    /**
     * 名称：成为校园推广大使
     */
    public function becomeSpread()
    {
        $user=$this->auth->user();
        $goodsNum=Depot::where('user_id',$user->id)->count();
        if($goodsNum<5){
            return $this->response->array([
                'status_code'=>201,
                'message'=>'抱歉您书店中还没有5本以上的书籍',
            ]);
        }

        //需要生成推广二维码
        $qrcode=app('wechat')->qrcode;
        $result = $qrcode->forever($user->id);
        $ticket = $result->ticket;
        $spread_qrcode = $qrcode->url($ticket);
        if(!$spread_qrcode){
            return $this->response->array([
                'status_code'=>201,
                'message'=>'抱歉，服务器正在开小差，请稍后再试',
            ]);
        }
        $user->spread_status=1;
        $user->spread_qrcode=$spread_qrcode;
        if(!$user->save()){
            return $this->response->array([
                'status_code'=>201,
                'message'=>'抱歉，服务器正在开小差，请稍后再试',
            ]);
        }

        return $this->response->array([
            'status_code'=>200,
            'message'=>'恭喜，你成为了校园推广大使',
        ]);



    }


}